<template>
  <div class="user-settings">
    <el-card class="settings-card">
      <template #header>
        <h3>账户设置</h3>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 基本信息设置 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            label-width="100px"
          >
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                :action="null"
                :http-request="uploadAvatar"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
              >
                <el-image
                  v-if="basicForm.avatar"
                  :src="basicForm.avatar"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="basicForm.nickname" placeholder="请输入昵称" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleBasicSubmit">保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 安全设置 -->
        <el-tab-pane label="安全设置" name="security">
          <el-form
            ref="securityFormRef"
            :model="securityForm"
            :rules="securityRules"
            label-width="100px"
          >
            <el-form-item label="手机号码">
              <span>{{ getCookieValue('displayPhone') || '未设置' }}</span>
            </el-form-item>
            <el-form-item label="验证码" prop="code">
              <div class="code-input">
                <el-input v-model="securityForm.code" placeholder="请输入验证码" />
                <el-button @click="handleSendCode" :disabled="isCodeSending">
                  {{ codeBtnText }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item label="新密码" prop="password">
              <el-input
                v-model="securityForm.password"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSecuritySubmit">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 账号绑定 -->
        <el-tab-pane label="账号绑定" name="binding">
          <div class="binding-list">
            <div class="binding-item">
              <div class="binding-info">
                <el-icon><Iphone /></el-icon>
                <div class="binding-detail">
                  <h4>手机绑定</h4>
                  <p>已绑定：{{ getCookieValue('displayPhone') || '未设置' }}</p>
                </div>
              </div>
            </div>
            <div class="binding-item">
              <div class="binding-info">
                <el-icon><Message /></el-icon>
                <div class="binding-detail">
                  <h4>邮箱绑定</h4>
                  <p>{{ userInfo.email ? `已绑定：${maskEmail(userInfo.email)}` : '未绑定' }}</p>
                </div>
              </div>
              <el-button link @click="handleUpdateEmail">
                {{ userInfo.email ? '修改' : '绑定' }}
              </el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      v-model="emailDialogVisible"
      :title="userInfo.email ? '修改邮箱' : '绑定邮箱'"
      width="400px"
    >
      <el-form :model="emailForm" :rules="emailRules" ref="emailFormRef" label-width="80px">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="emailForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div style="display: flex; gap: 10px;">
            <el-input v-model="emailForm.code" placeholder="请输入验证码" />
            <el-button @click="handleSendEmailCode" :disabled="emailCodeSending">
              {{ emailCodeBtnText }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="emailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEmailSubmit" :loading="emailSubmitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { Plus, Iphone, Message } from '@element-plus/icons-vue'
import { useUserStore } from '../../stores/modules/user'
import { sendSmsCode, changePassword, updateUserInfo } from '@/api/user'
import { getCookieValue } from '@/utils/request'

const userStore = useUserStore()
const activeTab = ref('basic')

// 用户信息
const userInfo = ref({
  id: userStore.userInfo?.id || '',
  telephone: userStore.userInfo?.telephone || '',
  email: userStore.userInfo?.email || '',
  nickName: userStore.userInfo?.nickName || '',
  icon: userStore.userInfo?.icon || ''
})

// 基本信息表单
const basicFormRef = ref(null)
const basicForm = reactive({
  avatar: userStore.userInfo?.icon || '',
  nickname: userStore.userInfo?.nickName || ''
})

// 基本信息验证规则
const basicRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 安全设置表单
const securityFormRef = ref(null)
const securityForm = reactive({
  phone: getCookieValue('phone') || '',
  code: '',
  password: ''
})

// 验证码按钮相关
const isCodeSending = ref(false)
const countdown = ref(60)
const codeBtnText = ref('获取验证码')
let timer = null

// 安全设置验证规则
const securityRules = {
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}

// 发送验证码
const handleSendCode = async () => {
  try {
    const phone = getCookieValue('phone')
    if (!phone) {
      ElMessage.error('请先登录或绑定手机号')
      return
    }
    
    isCodeSending.value = true
    await sendSmsCode(phone)
    ElMessage.success('验证码发送成功')
    countdown.value = 60
    timer = setInterval(() => {
      if (countdown.value > 0) {
        codeBtnText.value = `${countdown.value}秒后重新获取`
        countdown.value--
      } else {
        clearInterval(timer)
        isCodeSending.value = false
        codeBtnText.value = '获取验证码'
      }
    }, 1000)
  } catch (error) {
    isCodeSending.value = false
    ElMessage.error('验证码发送失败，请重试')
  }
}

// 提交安全设置
const handleSecuritySubmit = async () => {
  if (!securityFormRef.value) return
  
  await securityFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保所有必要字段都存在
        if (!securityForm.phone || !securityForm.password || !securityForm.code) {
          ElMessage.error('请填写完整信息')
          return
        }

        await changePassword({
          phone: securityForm.phone,
          password: securityForm.password,
          code: securityForm.code
        })
        
        ElMessage.success('密码修改成功')
        securityForm.code = ''
        securityForm.password = ''
      } catch (error) {
        console.error('密码修改失败:', error)
        ElMessage.error(error.message || '密码修改失败，请重试')
      }
    }
  })
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})

// 上传头像
const uploadAvatar = async (options) => {
  const { file, onSuccess, onError } = options
  try {
    // 显示加载状态
    const loadingInstance = ElLoading.service({
      text: '头像上传中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    // 使用Promise包装XMLHttpRequest
    const response = await new Promise((resolve, reject) => {
      const formData = new FormData()
      formData.append('file', file)
      
      const xhr = new XMLHttpRequest()
      xhr.open('POST', import.meta.env.VITE_API_BASE_URL + '/files/upload', true)
      
      // 添加token
      const token = userStore.accessToken
      if (token) {
        xhr.setRequestHeader('Authorization', `Bearer ${token}`)
      }
      
      // 添加uid
      const uid = getCookieValue('id')
      if (uid) {
        xhr.setRequestHeader('uid', uid)
      }
      
      xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText)
            resolve(response.data)
          } catch (e) {
            resolve(xhr.responseText)
          }
        } else {
          reject(new Error(`上传失败：${xhr.status} ${xhr.statusText}`))
        }
      }
      
      xhr.onerror = function() {
        reject(new Error('网络错误，上传失败'))
      }
      
      xhr.send(formData)
    })
    
    // 关闭加载状态
    loadingInstance.close()
    
    // 处理响应
    let avatarUrl = ''
    
    if (response && typeof response === 'string') {
      avatarUrl = response
    } else if (response && response.data) {
      avatarUrl = typeof response.data === 'string' ? response.data : response.data.url || response.data
    } else {
      avatarUrl = response
    }
    
    // 检查URL是否有效
    if (!avatarUrl) {
      throw new Error('上传成功但未获取到有效的图片URL')
    }
    
    // 更新头像URL
    basicForm.avatar = avatarUrl
    // 同时更新userInfo中的icon，确保保存时能够一起提交
    userInfo.value.icon = avatarUrl
    
    // 如果onSuccess回调存在则调用
    if (onSuccess) {
      onSuccess({ data: avatarUrl })
    }
    
    ElMessage.success('头像上传成功')
  } catch (error) {
    // 关闭可能存在的加载状态
    try {
      ElLoading.service().close()
    } catch (e) {
      // 忽略关闭加载状态时的错误
    }
    
    console.error('头像上传失败:', error)
    
    // 处理特定错误
    let errorMessage = '上传失败'
    
    if (error.response) {
      const status = error.response.status
      
      if (status === 401 || status === 403) {
        errorMessage = '权限不足或未登录，请重新登录后再试'
        // 可以在这里添加重定向到登录页的逻辑
      } else if (status === 413) {
        errorMessage = '文件太大，请选择小于2MB的图片'
      } else {
        errorMessage = `服务器错误 (${status}): ${error.response.data?.message || '未知错误'}`
      }
    } else {
      errorMessage = error.message || '网络连接问题，请稍后再试'
    }
    
    // 显示错误消息
    ElMessage.error(errorMessage)
    
    // 调用错误回调
    if (onError) {
      onError(error)
    }
  }
}

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 提交基本信息
const handleBasicSubmit = async () => {
  if (!basicFormRef.value) return
  
  await basicFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 使用已经更新过的userInfo中的icon值
        await updateUserInfo({
          id: userInfo.value.id,
          nickName: basicForm.nickname,
          icon: userInfo.value.icon, // 使用userInfo中的icon
          telephone: getCookieValue('phone'),
          email: userInfo.value.email
        })
        ElMessage.success('基本信息更新成功')
        // 更新本地存储的用户信息
        userStore.setUserInfo({
          ...userStore.userInfo,
          nickName: basicForm.nickname,
          icon: userInfo.value.icon // 使用userInfo中的icon
        })
      } catch (error) {
        console.error('更新失败:', error)
        ElMessage.error(error.message || '基本信息更新失败，请重试')
      }
    }
  })
}

// 手机号码脱敏
const maskPhone = (phone) => {
  return phone ? phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : ''
}

// 邮箱脱敏
const maskEmail = (email) => {
  if (!email) return ''
  const [username, domain] = email.split('@')
  const maskedUsername = username.charAt(0) + '****' + username.charAt(username.length - 1)
  return `${maskedUsername}@${domain}`
}

// 修改邮箱
const handleUpdateEmail = () => {
  emailForm.value.email = userInfo.value.email || ''
  emailForm.value.code = ''
  emailDialogVisible.value = true
}

const emailDialogVisible = ref(false)
const emailFormRef = ref(null)
const emailForm = ref({
  email: '',
  code: ''
})
const emailRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ]
}
const emailCodeSending = ref(false)
const emailCodeBtnText = ref('获取验证码')
const emailSubmitting = ref(false)
let emailTimer = null
const emailCountdown = ref(60)

// 发送邮箱验证码
const handleSendEmailCode = async () => {
  if (!emailForm.value.email) {
    ElMessage.error('请先输入邮箱')
    return
  }
  emailCodeSending.value = true
  // await sendEmailCode(emailForm.value.email) // 调用接口
  ElMessage.success('验证码已发送')
  emailCountdown.value = 60
  emailCodeBtnText.value = '60秒后重试'
  emailTimer = setInterval(() => {
    emailCountdown.value--
    emailCodeBtnText.value = `${emailCountdown.value}秒后重试`
    if (emailCountdown.value <= 0) {
      clearInterval(emailTimer)
      emailCodeSending.value = false
      emailCodeBtnText.value = '获取验证码'
    }
  }, 1000)
}

// 提交邮箱绑定/修改
const handleEmailSubmit = async () => {
  if (!emailFormRef.value) return
  await emailFormRef.value.validate(async (valid) => {
    if (valid) {
      emailSubmitting.value = true
      try {
        // await updateEmail(emailForm.value) // 调用接口
        userInfo.value.email = emailForm.value.email // 本地赋值
        ElMessage.success('邮箱绑定成功')
        emailDialogVisible.value = false
      } catch (error) {
        ElMessage.error('邮箱绑定失败')
      } finally {
        emailSubmitting.value = false
      }
    }
  })
}

// 清理定时器
onUnmounted(() => {
  if (emailTimer) clearInterval(emailTimer)
})
</script>

<style scoped>
.user-settings {
  width: 100%;
}

.settings-card {
  margin-bottom: 20px;
}

.avatar-uploader {
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.binding-list {
  padding: 20px 0;
}

.binding-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.binding-item:last-child {
  border-bottom: none;
}

.binding-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.binding-info .el-icon {
  font-size: 24px;
  color: var(--el-color-primary);
}

.binding-detail h4 {
  margin: 0 0 5px;
  font-size: 16px;
}

.binding-detail p {
  margin: 0;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
.code-input {
  display: flex;
  gap: 10px;
}

.code-input .el-input {
  flex: 1;
}

.code-input .el-button {
  width: 120px;
}
</style>